package epam.marchenko.library.services;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import epam.marchenko.library.domain.Book;
import epam.marchenko.library.domain.BookClass;
import epam.marchenko.library.domain.OutcomeRecord;
import epam.marchenko.library.repository.BookClassRepository;
import epam.marchenko.library.repository.BookRepository;
import epam.marchenko.library.repository.OutcomeRecordRepository;

@Service
public class BookServiceImpl implements BookService {

	@Autowired
	BookClassRepository bookClassRep;
	@Autowired
	OutcomeRecordRepository orRep;
	@Autowired
	BookRepository bookRep;
	
	public List<BookClass> getAllBookClasses() {
		return bookClassRep.findAll();
	}

	public Map<BookClass, Integer> getBooksWithAvailableCount() {
		
		Map<BookClass, Integer> result = new HashMap<BookClass, Integer>();
		List<BookClass> bclasses = bookClassRep.findAll();
		for (BookClass bc:bclasses) {
			List<Book> blist = bookRep.findAllForClass(bc);
			List<OutcomeRecord> orlist = orRep.findForClass(bc);
			int count = blist.size();
			for (OutcomeRecord or:orlist) {
				if (or.isActive()) count--;
			}
			result.put(bc, count);
			}
		
		return result;
	}

	@Override
	public boolean bookIsAvailable(Book book) {
		List<OutcomeRecord> lorders = orRep.findForBook(book);
		for (OutcomeRecord or:lorders) {
			if (or.isActive()) return false;
		}
		return true;
	}

	@Override
	public BookClass getBookClassById(int id) {
		return bookClassRep.findById(id);
	}

	@Override
	public List<Book> getAvailableBooksForClass(BookClass bclass) {
		List<Book> blist = bookRep.findAllForClass(bclass);
		List<OutcomeRecord> orlist = orRep.findForClass(bclass);
		
		for (OutcomeRecord or:orlist) {
			if (or.isActive()) {
				blist.remove(or.getBook());
			}
		}
		
		return blist;
	}

}
